#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import define
import excel
import record


def cell2Value(cell_v):
    if cell_v.ctype == 2:  # int
        return str(int(cell_v.value))
    return cell_v.value


def lineData2Record(bean, line):
    r = record.Record({}, [])
    for var in bean.getVars():
        if var.getType() == 'vector':
            vector = record.Vector(var.getName(), var.getValue(), values=[])
            r.getVecs().append(vector)
            for col in var.getFromCol().split(','):
                value = line[col]
                if var.getValue() == 'int':
                    vector.getValues().append(cell2Value(value))
                else:
                    vector.getValues().append(value)
        else:
            value = line[var.getFromCol()]
            if var.getType() == 'int':
                r.getFields()[var.getName()] = cell2Value(value)
            else:
                r.getFields()[var.getName()] = value
    return r


def beginParse():
    dio = define.DefineIO('define.xml')
    beans = dio.read()  # 从define中读出元数据

    for bean in beans:
        excelFileName = bean.getFromFile()
        ex = excel.Excel(excelFileName)
        excelDatas = ex.parse2xml()  # 获取excel数据

        records = [lineData2Record(bean, line) for line in excelDatas]
        xmlWriter = excel.XmlWriter(bean.getName())
        xmlWriter.writeData2Xml(records)


if __name__ == '__main__':
    beginParse()
